package server.util;

import base.BaseValue;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpUtils {
    /**
     * 发送Get请求
     *
     * @param url    请求的接口
     * @param token  用于验证身份，登录时设为null即可
     * @param params 用于传递文本信息
     * @return 请求得到的文本
     */
    public static String get(String url, String token, Map<String, String> params) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            //拼接url
            if (params != null) {
                StringBuilder urlBuilder = new StringBuilder(url + "?");
                for (Map.Entry<String, String> param : params.entrySet()) {
                    urlBuilder.append(param.getKey()).append("=").append(param.getValue()).append("&");
                }
                url = urlBuilder.toString();
                url = url.substring(0, url.length() - 1);
            }

            System.out.println(url);
            HttpGet httpGet = new HttpGet(url);

            //设置token
            httpGet.setHeader("Token", token);

            //System.out.println("executing request " + httpGet.getRequestLine());
            //建立连接
            try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
                //System.out.println("----------------------------------------");
                //System.out.println(response.getStatusLine());
                //判断连接是否成功
                if (response.getStatusLine().getStatusCode() != 200) {
                    return "";
                }
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    String answer = EntityUtils.toString(resEntity);
                    //System.out.println("返回数据： " + answer);
                    EntityUtils.consume(resEntity);
                    return answer;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpclient != null) httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    /**
     * 发送post请求
     *
     * @param url    请求接口
     * @param token  token,用于验证身份
     * @param params 用于传递文本信息,Map<String,String>形式
     * @param files  用于传递文件,Map<String, File>形式
     * @return 返回请求得到的文本
     */
    public static String post(String url, String token, Map<String, String> params, Map<String, File> files) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost post = new HttpPost(url);
            //装配请求参数
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            if (files != null) {
                for (Map.Entry<String, File> file : files.entrySet()) {
                    builder.addPart(file.getKey(), new FileBody(file.getValue()));
                }
            }
            if (params != null) {
                for (Map.Entry<String, String> param : params.entrySet()) {
                    System.out.println(param.getKey());
                    //builder.addPart(param.getKey(), new StringBody(param.getValue(), ContentType.APPLICATION_JSON));
                    builder.addTextBody(param.getKey(), param.getValue(), ContentType.APPLICATION_JSON);
                }
            }

            //创建请求的entity
            HttpEntity requestEntity = builder.build();

            post.setEntity(requestEntity);
            //设置token
            post.setHeader("Token", token);

            System.out.println("executing request " + post.getRequestLine());

            try (CloseableHttpResponse response = httpClient.execute(post)) {
                //System.out.println("----------------------------------------");
                //System.out.println(response.getStatusLine());
                //判断连接是否成功
                if (response.getStatusLine().getStatusCode() != 200) {
                    System.out.println("请求失败： " + response.getStatusLine());
                    return "";
                }
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    String answer = EntityUtils.toString(responseEntity);
                    EntityUtils.consume(responseEntity);
                    //System.out.println("返回数据： " + answer);
                    return answer;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    /**
     * 发送post请求
     *
     * @param url    请求接口
     * @param token  token,用于验证身份
     * @param params 用于传递文本信息,Map<String,String>形式
     * @return 返回请求得到的文本
     */
    public static String post(String url, String token, Map<String, String> params) {
        //初始化连接
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //声明post请求
        HttpPost post = new HttpPost(url);
        List<NameValuePair> pairs = new ArrayList<>();
        //建造一个装有数据的实体对象
        HttpEntity entity = null;
        try {
            //填充参数
            if (params != null && params.size() > 0) {
                for (Map.Entry<String, String> param : params.entrySet()) {
                    pairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
            }
            entity = new UrlEncodedFormEntity(pairs, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //为post装配数据
        post.setEntity(entity);
        //设置token
        post.addHeader("Token", token);
        post.addHeader("Content-Type","application/x-www-form-urlencoded");
        post.addHeader("Connection", "Keep-Alive");
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(post);
            if (response.getStatusLine().getStatusCode() != 200) {
                System.out.println("请求错误： " + response.getStatusLine().getReasonPhrase());
                return "";
            }
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                String result = EntityUtils.toString(responseEntity, "UTF-8");
                EntityUtils.consume(responseEntity);
                return result;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
}
